<template>
  <div class="box">
    <div class="top">
      <div class="topL">
        <el-button type="primary" plain :icon="Plus" @click="subadd">新增</el-button>
        <el-button type="success" plain :icon="Edit">修改</el-button>
        <el-button type="danger" plain :icon="Delete">删除</el-button>
        <el-button type="warning" plain :icon="Upload" @click="exportExcel">导出</el-button>
      </div>
      <div class="topR">
        <el-button :icon="Search" circle />
        <el-button :icon="Refresh" circle />
      </div>
    </div>
    <div style="margin-top: 20px;">
      <el-tag>待处理任务列表</el-tag>
    </div>
    <div>
      <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column property="name" label="客户姓名" width="150">
          <!-- <template #default="scope">{{ scope.row.date }}</template> -->
        </el-table-column>
        <el-table-column property="phone" label="手机号码" width="150" />
        <el-table-column property="channelName" label="渠道名称" width="150" show-overflow-tooltip />
        <el-table-column property="activityName" label="活动名称" width="150" show-overflow-tooltip />
        <el-table-column property="courseName" label="课程名称" width="150" show-overflow-tooltip />
        <el-table-column property="contractPrice" label="合同金额" width="150" show-overflow-tooltip />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">查看</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">预览</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pages">
        <div></div>
        <div class="page">
          <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4"
            :page-sizes="[10, 20, 30, 40]" :background="background" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <div class="middle">

      <el-tag class="ml-2" type="success"> 已提交未审核任务列表</el-tag>
      <div>

        <el-table ref="multipleTableRef" :data="tableDatas" style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column property="name" label="客户姓名" width="150">
            <!-- <template #default="scope">{{ scope.row.date }}</template> -->
          </el-table-column>
          <el-table-column property="phone" label="手机号码" width="150" />
          <el-table-column property="channelName" label="渠道名称" width="150" show-overflow-tooltip />
          <el-table-column property="activityName" label="活动名称" width="150" show-overflow-tooltip />
          <el-table-column property="courseName" label="课程名称" width="150" show-overflow-tooltip />
          <el-table-column property="contractPrice" label="合同金额" width="150" show-overflow-tooltip />
        </el-table>
        <div class="pages">
          <div></div>
          <div class="page">
            <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4"
              :page-sizes="[10, 20, 30, 40]" :background="background" layout="total, sizes, prev, pager, next, jumper"
              :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </div>
      </div>
    </div>






    <div class="middle">

      <el-tag class="ml-2" type="danger">审核完成任务列表</el-tag>
      <div>

        <el-table ref="multipleTableRef" :data="tableDatas" style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column property="name" label="客户姓名" width="150">
            <!-- <template #default="scope">{{ scope.row.date }}</template> -->
          </el-table-column>
          <el-table-column property="phone" label="手机号码" width="150" />
          <el-table-column property="channelName" label="渠道名称" width="150" show-overflow-tooltip />
          <el-table-column property="activityName" label="活动名称" width="150" show-overflow-tooltip />
          <el-table-column property="courseName" label="课程名称" width="150" show-overflow-tooltip />
          <el-table-column property="contractPrice" label="合同金额" width="150" show-overflow-tooltip />
          <el-table-column property="contractPrice" label="备注信息" width="150" show-overflow-tooltip />
          <el-table-column property="contractPrice" label="操作" show-overflow-tooltip />
        </el-table>
        <div class="pages">
          <div></div>
          <div class="page">
            <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4"
              :page-sizes="[10, 20, 30, 40]" :background="background" layout="total, sizes, prev, pager, next, jumper"
              :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </div>
      </div>
    </div>
    <div class="shows" v-if="cbd">
      <div class="contents">
        <div class="top">
          <span style="font-size: 20px;">添加合同</span>
          <CloseBold @click="cc" style="width: 1em; height: 1em; margin-right: 8px" />

        </div>
        <div class="ipts">

          <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
            :size="formSize" status-icon>
            <div class="form">
              <el-form-item label="手机号码" prop="name">
                <el-input @blur="handleInputBlur(ruleForm.name)" style="width: 170px;" placeholder="请输入手机号"
                  v-model="ruleForm.name" />
              </el-form-item>
              <el-form-item label="客户姓名" prop="cname">
                <el-input style="width: 170px;" disabled placeholder="请输入客户姓名" v-model="ruleForm.cname" />
              </el-form-item>
              <el-form-item label="渠道来源" prop="source">
                <el-input style="width: 170px;" disabled placeholder="渠道来源" v-model="ruleForm.source" />
              </el-form-item>
              <el-form-item label="活动信息" prop="message">
                <el-input style="width: 170px;" disabled placeholder="活动信息" v-model="ruleForm.message" />
              </el-form-item>
              <el-form-item label="课程分类" prop="categorys">
                <el-input style="width: 170px;" disabled placeholder="课程分类" v-model="ruleForm.categorys" />
              </el-form-item>
              <el-form-item label="购买课程" prop="coures">
                <el-input style="width: 170px;" disabled placeholder="请选择" v-model="ruleForm.coures" />
              </el-form-item>
              <el-form-item label="审批部门" prop="category" style="width: 290px;">
                <el-tree-select v-model="ruleForm.category" :data="data" :props="defaultProps" placeholder="请选择课程分类"
                  style="width: 300px" check-strictly clearable @change="onTreeSelectChange" />
              </el-form-item>



              <el-form-item label="审批人" prop="human">
                <el-select v-model="ruleForm.human" placeholder="Select" style="width: 170px"
                  @change="handleHumanChange">
                  <el-option v-for="item in optionss" :key="item.userName" :label="item.nickName"
                    :value="item.userName" />
                </el-select>
              </el-form-item>
              <el-form-item label="合同价格" prop="count" style="height: 32px;">
                <el-input-number v-model="ruleForm.count" :min="1" @change="handleChange" placeholder="合同价格" />
              </el-form-item>

              <el-form-item label="合同文件" style="width: 300px;">
                <el-upload v-model:file-list="fileList" class="upload-demo"
                  action="http://47.104.167.34:9100/dev-api/tienchin/contract/upload" multiple
                  :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :limit="3"
                  :on-exceed="handleExceed">
                  <el-button type="primary">选择合同原件</el-button>
                  <template #tip>
                    <div class="el-upload__tip">

                      合同原件大小不能超过 5MB.
                    </div>
                  </template>
                </el-upload>
              </el-form-item>

              <el-form-item></el-form-item>

              <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                  确定
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">取消</el-button>
              </el-form-item>

            </div>
          </el-form>

        </div>
      </div>
    </div>




    <div class="show" v-if="abc">
      <div class="content">
        <div class="top">
          <span style="font-size: 20px;">合同详情</span>
          <CloseBold @click="cc" style="width: 1em; height: 1em; margin-right: 8px" />
        </div>
        <div class="article">
          <div class="ids">
            <div>合同编号</div>
            <span>{{ idos }}</span>
          </div>
          <div class="ids">
            <div>电话</div>
            <span>{{ phone }}</span>
          </div>
          <div class="ids">
            <div>客户姓名</div>
            <span>{{ names }}</span>
          </div>
          <div class="ids">
            <div>课程分类</div>
            <span>450</span>
          </div>
          <div class="ids">
            <div>课程名</div>
            <span>{{ courseName }}</span>
          </div>
          <div class="ids">
            <div>渠道名称</div>
            <span>{{ channelName }}</span>
          </div>
          <div class="ids">
            <div>活动名称</div>
            <span>{{ activityName }}</span>
          </div>
          <div class="ids">
            <div>合同状态</div>
            <span>{{ status }}</span>
          </div>
          <div class="ids">
            <div>合同金额</div>
            <span>{{ contractPrice }}</span>
          </div>
          <div class="ids">
            <div>课程价格</div>
            <span>{{ price }}</span>
          </div>
          <div class="ids">
            <div>折扣类型</div>
            <span>{{ discountType }}</span>
          </div>
          <div class="ids">
            <div>合同审批人</div>
            <span>{{ approveUserName }}</span>
          </div>
        </div>
        <div class="btn">
          <el-button type="primary" @click="cc">确定</el-button>
        </div>
      </div>


    </div>

  </div>
</template>

<script lang="ts" setup>
import { Login, tree, add } from '../../../utils/api';
import axios from 'axios';
import Cookies from 'js-cookie'
import { Delete, Plus, Edit, Upload, Search, Refresh } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ref, reactive, toRaw } from 'vue'
import type { FormInstance, FormRules  } from 'element-plus';
import { ElTable,ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'


const abc = ref(false)
const cbd = ref(false)
const currentPage4 = ref(1)

const pageSize4 = ref(10)

const background = ref(false)
const total = ref<Number>(10)
const idos = ref<any>()
const names = ref<string>('')
const activityName = ref<string>('')
const approveUserName = ref<string>('')
const channelName = ref<string>('')
const contractPrice = ref<string>('')
const courseName = ref<string>('')
const phone = ref<string>('')
const price = ref<Number>()
const status = ref<any>()
const discountType = ref<any>()
const num = ref()
const num1 = ref()
const num2 = ref()
const num3 = ref()
const num4 = ref()
const num5 = ref()
const num6 = ref()
const num7 = ref()

interface RuleForm {
  name: string,//手机号码
  category: string,//二级联动
  human: string,//审批人
  cname: string,//客户姓名
  source: string,//渠道来源
  message: string,//活动信息
  categorys: string,//课程分类
  coures: string//课程
  count: Number
}

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  name: '',
  category: '',
  human: '',
  cname: '',
  source: '',
  message: '',
  categorys: '',
  coures: '',
  count: '5'

})

interface User {

  name: string,
  phone: string,
  channelName: string,
  activityName: string,
  courseName: string,
  contractPrice: string

}

interface Tree {
  label: string
  children?: Tree[]
}

const handleNodeClick = (data: Tree) => {
  console.log(data)
}
const data = ref<Tree[]>([])
const value = ref('')
const optionss = ref<Array<any>>([])
const authToken = Cookies.get('Admin-Token');


const exportExcel = async () => {
  const res = await axios.post(
    'http://47.104.167.34:9100/prod-api/tienchin/course/export',
    { pageNum: 1, pageSize: 10 },
    {
      headers: {
        Authorization: 'Bearer ' + authToken
      },
      responseType: 'blob' // 关键点！
    }
  )
  saveAs(res.data, '导出数据.xlsx')
}


const handleInputBlur = (value) => {
  console.log('点击时输入框的值:', value)
  axios.get(`
http://47.104.167.34:9100/prod-api/tienchin/contract/customer/${ruleForm.name}`, {
    headers: {
      Authorization: 'Bearer ' + authToken
    }
  }).then((res => {
    console.log(res.data.data);
    ruleForm.cname = res.data.data.name
    ruleForm.source = res.data.data.channelName
    ruleForm.message = res.data.data.activityName
    ruleForm.coures = res.data.data.courseName
    num4.value = res.data.data.activityId
    num5.value = res.data.data.channelId
    num6.value = res.data.data.courseId
    num7.value = res.data.data.type

    ruleForm.categorys = res.data.data.discountType == 2 ? '游泳类' : '其他'
  }))
}


function subadd(){
  cbd.value=true
}

const handleHumanChange = (userName) => {
  const selected = optionss.value.find(item => item.userName === userName)
  console.log('选中的审批人对象:', selected)
  const death = toRaw(selected)
  num.value = death.deptId
  num1.value = death.nickName
  num2.value = death.userId
  num3.value = death.userName
}

function treelist() {
  tree({}).then((res) => {
    console.log(res);
    data.value = res.data

  })
}
treelist()

const onTreeSelectChange = (val) => {
  optionss.value = []
  ruleForm.human = ''
  axios.get(`http://47.104.167.34:9100/prod-api/tienchin/contract/users/${val}`, {
    headers: {
      Authorization: 'Bearer ' + authToken
    }
  }).then((res) => {
    optionss.value = res.data.data
  })
}
const defaultProps = {
  children: 'children',
  label: 'label',
  value: 'id'
}

const handleChange = (value: number) => {
  console.log(value)
}
const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '手机号码不能为空', trigger: 'blur' },
    { min: 11, max: 11, message: '不符合手机号规范', trigger: 'blur' },

  ],

})


const fileList = ref<UploadUserFile[]>([

])

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
    } totally`
  )
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}


const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      add({
        activityId: num4.value,
        activityName: ruleForm.message,
        approveDeptId: num.value,
        approveUserId: num2.value,
        approveUserName: num3.value,
        channelId: num5.value,
        channelName: ruleForm.source,
        contractPrice: ruleForm.count,
        courseId: num6.value,
        courseName: ruleForm.coures,
        departmentId: num.value,
        discountType: ruleForm.categorys == '游泳' ? 2 : 0,    //ruleForm.categorys
        name: ruleForm.cname,
        nickName: num1.value,
        phone: ruleForm.name,
        type: num7.value
      }).then((res) => {
        console.log(res);
        cbd.value = false

      })
      ElMessage({
        message: '创建成功',
        type: 'success',
      })
      getlist()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  cbd.value = false
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))


const coursePrice = ref<string>('')
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)


}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}


function cc() {
  abc.value = false
  cbd.value=false
}
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<User[]>([])
const toggleSelection = (rows?: User[]) => {
  if (rows) {
    rows.forEach((row) => {
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comm
      multipleTableRef.value!.toggleRowSelection(row, undefined)
    })
  } else {
    multipleTableRef.value!.clearSelection()
  }
}
const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val
}

const tableData = ref<User[]>([])
const tableDatas = []

function getlist() {
  Login({}).then((res) => {
    console.log(res.rows)
    tableData.value = res.rows // 这样页面才会响应式更新
    total.value = res.total
  })
}

const handleEdit = (index: number, row: User) => {
  abc.value = true
  console.log(index, row.contractId)
  axios.get(`http://47.104.167.34:9100/prod-api/tienchin/contract/views/${row.contractId}`,
    {
      headers: {
        Authorization: 'Bearer ' + authToken
      }
    }
  ).then((res) => {
    console.log(res);
    names.value = res.data.data.name
    activityName.value = res.data.data.activityName
    approveUserName.value = res.data.data.approveUserName
    channelName.value = res.data.data.channelName
    contractPrice.value = res.data.data.contractPrice
    courseName.value = res.data.data.courseName == 999 ? '游泳课' : '其他'
    phone.value = res.data.data.phone
    idos.value = res.data.data.contractId
    price.value = res.data.data.coursePrice
    status.value = res.data.data.status == 0 ? '已审核' : '未审核'
    discountType.value = res.data.data.discountType == 2 ? '代金券' : '其他'

  })

}
const handleDelete = (index: number, row: User) => {
  console.log(index, row)
}
getlist()
</script>

<style lang="scss" scoped>
.box {
  padding: 20px;
}

.top {
  display: flex;
  justify-content: space-between;
}

.pages {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  padding-bottom: 5px;
  border-bottom: 1px solid rgba(128, 128, 128, 0.4);
}

.middle {
  padding-top: 20px;
}

.show,
.shows {
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  position: fixed;
  z-index: 20;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.content {
  width: 600px;
  height: 350px;
  background-color: #fff;
  padding: 20px;
  position: absolute;
  bottom: 0;
  left: 0;
  top: 0;
  right: 0;
  margin: auto;
}

.contents {
  width: 620px;
  height: 390px;
  background-color: #fff;
  padding: 20px;
  position: absolute;
  bottom: 0;
  left: 0;
  top: 0;
  right: 0;
  margin: auto;

}

.article {
  margin-top: 40px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  justify-content: space-between;
}

.ids {
  width: 180px;
  margin: 5px 0;
}

.ids div:first-child {
  font-style: italic;
  font-weight: 600;
}

.ids span {
  color: gray;
  font-size: 14px;
}

.btn {
  text-align: right;
}

.form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
</style>